package com.Filter;

/**
 * @Author: 34-蔡越恺
 * @Description : [一句话描述这个类的作用]
 * @Version : [v1.1]
 * @Date: 2024/6/26
 * @Time: 16:24
 */

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);

        String uri = req.getRequestURI();
        if (uri.endsWith("login.html") || uri.endsWith("loginServlet")) {
            chain.doFilter(request, response);
            return;
        }

        if (session != null && session.getAttribute("username") != null) {
            chain.doFilter(request, response);
        } else {
            resp.sendRedirect("login.html");
        }
    }

    @Override
    public void destroy() {

    }
}

